package com.lwei.ljpro.service.impl;

import com.lwei.ljpro.dao.IBaseDao;
import com.lwei.ljpro.entry.BaseEntry;
import com.lwei.ljpro.service.IBaseService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.List;

@Service
public abstract class BaseServiceImpl<T extends BaseEntry> implements IBaseService<T> {
    private Logger logger = LoggerFactory.getLogger("BaseService");

    @Autowired
    private IBaseDao<T> baseDao;

    protected abstract String getKey();

    @Override
    public Long save(T t) {
        Long id = null;
        //新增时加上时间记录
        t.setCreateDate(new Date());
        t.setModifyDate(new Date());
        if(t.getId() == null){
            id = baseDao.save(getKey(), t);
        }else{
            Boolean save = baseDao.saveById(getKey(), t.getId(), t);
            if(save){
                id = t.getId();
            }
        }
        return id;
    }

    @Override
    public T update(Long id, T t) {
        t.setModifyDate(new Date());
        return baseDao.update(getKey(), id, t);
    }

    @Override
    public T getEntryById(Long id) {
        return baseDao.findOneById(getKey(), id);
    }

    @Override
    public Boolean delete(Long id) {
        try {
            baseDao.delete(getKey(), id);
            return true;
        } catch (NullPointerException ignored){
            return false;
        }
    }

    @Override
    public List<T> listEntryAll(String key) {
        return baseDao.listEntryAll(key);
    }
}
